<?php
include_once 'field.class.php';

class field_tag extends field
{
    public $error;
    protected $fieldname = '标签';
    private $table;

    public function __construct($field = '')
    {
        parent::__construct($field);
        $this->table = DB_PRE . 'tags';
    }

    /**
     * 生成设置项
     * @author menghao
     * @param <string> $data
     * @return <string>
     */
    function settings($data='')
    {
        $data = unserialize($data);
        $data['size'] = isset($data['size']) && is_numeric ($data['size']) ? $data['size'] : 50;
        
        $setting = '';
        $setting .= '<label>文本框长度：'.form::text('settings[size]', 'setting_size', $data['size'], 7).'</label> ';
        return $setting;
    }


    /**
     * 检查设置项数据
     * @author menghao
     * @param <array> $data 
     */
    function check_settings($data)
    {
        if(!is_numeric($data['size']))
        {
            $this->error = "文本框长度必须是数字";
            return false;
        }
        return true;
    }

    function get_data($data)
    {
        $this->save_tags($data);
        return $data;
    }

    function save_tags($data)
    {
        global $db;
        $table = $this->table;
        $data = trim($data);
        if(empty($data))
        {
            return true;
        }
        
        $tags = explode(' ', $data);
        $saved = array();
        foreach($tags as $tg)
        {
            $tg = trim($tg);
            if(empty($tg) || $saved[$tg]) continue;
            $db->prepare("select * from $table where status=? and tag=?");
            $db->set_int(STATUS_NORMAL);
            $db->set_string($tg);
            $tag_info = $db->execute(true);
            
            if(empty($tag_info))
            {
                $db->insert($table, array('tag' => $tg, 'count'=> 1));
            }
            else
            {
                $tag_info['count'] = intval($tag_info['count']);
                $db->simple_update($table, array('count'=>$tag_info['count']+1), array('tag'=>$tg));
            }
            $saved[$tg] = true;
        }
        return true;
    }

    function get_top_tags()
    {
        $table_tag = $this->table;
        $data = get("select * from $table_tag where status=".STATUS_NORMAL." order by count desc", 10);
        $return = array(''=>'常用标签');
        foreach($data as $r)
        {
            $return[$r['tag']] = $r['tag'];
        }
        return $return;
    }

    function create_form($value='')
    {
        $field = $this->field_data['field'];
        $size = $this->field_data['settings']['size'];
        $tags = $this->get_top_tags();
        $form = form::text("data[$field]", "data_$field", $value, $size);
        $form .= form::select($tags, 'select_tags');
        $form .= "<script>$('#select_tags').change(function(){
                    $('#data_$field').val($('#data_$field').val()+' '+$(this).val() );
                 });</script>";
        return $form;
    }
}
?>